package yuan.node;

import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.api.BackgroundCallback;
import org.apache.curator.framework.api.CuratorEvent;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.ZooDefs;
import org.apache.zookeeper.data.ACL;
import org.apache.zookeeper.data.Id;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.util.ArrayList;

/**
 * @version: 1.0
 * @Description: TODO
 * @author: zZmH
 * @date: 2020/09/12 20:26
 */


public class CuratorCreate {
    public static final String ip = "192.168.190.128:2181";
    CuratorFramework client;

    @Before
    public void before() {
        RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 3);
        client = CuratorFrameworkFactory.builder().connectString(ip).sessionTimeoutMs(5000).retryPolicy(retryPolicy).namespace("create").build();
        client.start();
    }

    @After
    public void after() {
        client.close();
    }

    @Test
    public void create1() throws Exception {
        client.create()
                .withMode(CreateMode.PERSISTENT)
                .withACL(ZooDefs.Ids.OPEN_ACL_UNSAFE)
                .forPath("/noded1", "nodes".getBytes());
        System.out.println("end");

    }
    @Test
    public void create2() throws Exception {
        ArrayList<ACL> acls = new ArrayList<>();
        Id id = new Id("ip", "127.0.0.1");
        acls.add(new ACL(ZooDefs.Perms.ALL, id));
        client.create()
                .withMode(CreateMode.PERSISTENT)
                .withACL(acls)
                .forPath("/node", "ndsf".getBytes());


    }@Test
    public void create3() throws Exception {
        //递归创建
        client.create()
                .creatingParentsIfNeeded()
                .withMode(CreateMode.PERSISTENT)
                .withACL(ZooDefs.Ids.OPEN_ACL_UNSAFE)
                .forPath("/nodez/nodez2", "dfe".getBytes());
        System.out.println("end");

    }@Test
    public void create4() throws Exception {
        //异步方式创建
        client.create()
                .withMode(CreateMode.PERSISTENT)
                .withACL(ZooDefs.Ids.OPEN_ACL_UNSAFE)
                .inBackground(new BackgroundCallback() {
                    @Override
                    public void processResult(CuratorFramework curatorFramework, CuratorEvent curatorEvent) throws Exception {
                        System.out.println(curatorEvent.getPath());
                        System.out.println(curatorEvent.getType());
                    }
                })
                .forPath("/nodee4","dfe".getBytes());
        Thread.sleep(5000);
        System.out.println("end");
    }@Test
    public void create5(){


    }@Test
    public void create6(){


    }


}
